#!/bin/python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    By :陈狍子 e4ting@qq.com 2024-12-07 22:19:00
"""
import sys,os,time
from pdb import set_trace as strace
from traceback  import format_exc as dumpstack
from e4ting import util,log

from .cash         import Utxo,VirtualAccount
from core.control  import Notify,Caller
from core.cache    import PlayerCache
from models.mysqls import ModelCash,ModelRoom,ModelRoomSeat,db

class GamePlayer(object):
    """游戏玩家"""
    def __init__(self, index=0, uid="", auto=True):
        self.index = index
        self.uid   = uid
        self.faces = []
        self.score = None
        self.cash  = VirtualAccount(uid=self.uid).init()
        # self.cache = {}
        self.auto  = auto

    def set_room(self, room):
        self.room  = room
        self.sender= room.sender
        return self

    @property
    def cache(self):
        cache = PlayerCache(self.uid)
        if not cache.exists():
            cache.set(__time__=util.now())
        return cache

    def webdump(self):
        return dict(uid=self.uid, index=self.index, rpc=f'e4ting.{self.uid}.bet')

    def face_dump(self):
        return [face.webdump() for face in self.faces]

    def rate_dump(self):
        if not self.score:
            return {}
        return self.score.webdump()

    def do_deal_cards(self, cards):
        self.faces = cards
        # self.sender.all_hands(data)
        self.room.send_all_hands()

    def set_score(self, score):
        self.score = score
        self.room.send_all_rate()

    def remote_bet(self, minimum):
        if self.auto:
            return minimum
        string = input("[ {self} ]请输入下注金额(不得小于 {minimum}): ".format(self=self, minimum=minimum))
        return int(string.strip() or minimum)

    def sleep(self, sec=1):
        for i in range(sec + 1):
            self.room.send_progress(self.index, int(100*i/sec))
            time.sleep(1)

    def do_bet(self, minimum=0, Round=None, force=False):
        log.info("{self} 最少应该下注 {bet} force={force}".format(self=self, bet=minimum, force=force))

        if force:
            amount = minimum
        else:
            self.sleep(1)
            amount = self.remote_bet(minimum)

        if not amount:
            return 0
        # ret = self.cash.withdraw(amount)
        # strace()
        utxo = Utxo(who=self.cash, to=Round.game.judge.account, room=self.room, game=Round.game, Round=Round)
        ret  = utxo.do_withdraw(amount, reason=f"下注:房间{self.room.uid}-局{Round.game.uid}-回合{Round}")
        # self.room.game
        if ret == False:
            return 0
        return amount

    def incr_bet(self):
        # 累加下注记录
        amount = self.get("bet", 0)
        # strace()
        return self.set("total_bet", amount)

    def get(self, key, default=0):
        attr = self.cache.get(key)
        if attr is None:
            return default
        if attr.isdigit():
            return int(attr)
        return attr

    def set(self, key, value):
        if type(value) is int:
            self.cache.change(**{key:value})
        else:
            self.cache.set(**{key:value})

    def clear_cache(self, *key):
        if not key:
            key = ("bet", "raise", "blind_raise")
        self.cache.delete(*key)
        # if key:
        #     if key in self.cache:
        #         del self.cache[key]
        #         self.cache.delete(key)
        # else:
        #     self.cache = {}

    def get_seat_record(self):
        if item := db.session.query(ModelRoomSeat).filter( ModelRoomSeat.uid==self.uid ).first():
            log.info(item)
            return item
        return None

    def __lt__(self, other):
        return self.score < other.score

    def __ge__(self, other):
        return self.score >= other.score

    def __le__(self, other):
        return self.score <= other.score

    def __repr__(self):
        if self.score:
            return "{self.uid} 号玩家 {self.score.type} {self.score.score} {self.faces} {self.cache}".format(self=self)
        if self.faces:
            return "{self.uid} 号玩家 {self.faces} {self.cache}".format(self=self)
        return "{self.uid} 号玩家 {self.cache}".format(self=self)


